<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="800px">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="资源名称" prop="knowName">
        <el-input v-model="formData.knowName" placeholder="请输入资源名称" />
      </el-form-item>
      <el-form-item label="章节" prop="chapter">
        <el-input-number v-model="formData.chapter" :min="1" :max="50"  placeholder="请输入章节"  />
      </el-form-item>
      <el-form-item label="适配书籍" prop="bookId">
        <el-select
          placeholder="选择书籍"
          v-model="formData.bookId"
          class="m-2"
          size="large"
          style="width: 240px"
          @change="choiceOption"
        >
          <el-option
            v-for="item in bookList"
            :key="item.id"
            :label="item.bookName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>


      <el-form-item label="资源上传" prop="knowUrl">
        <UploadFile v-model="formData.knowUrl" :limit="1" :fileType="['pdf']" :fileSize="10"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">

import { KnowledgeApi, KnowledgeVO } from '@/api/xhyy/knowledge'
import {BookApi} from "@/api/xhyy/book";

/** 知识点 表单 */
defineOptions({ name: 'KnowledgeForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  knowName: undefined,
  chapter: undefined,
  bookId: undefined,
  grade: undefined,
  bookName: undefined,
  knowUrl: '',
})
const formRules = reactive({
  bookId: [{ required: true, message: '绑定的教材不能为空', trigger: 'blur' }],
  bookName: [{ required: true, message: '书籍名称不能为空', trigger: 'blur' }],
  knowUrl: [{ required: true, message: '资源地址不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await KnowledgeApi.getKnowledge(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as KnowledgeVO
    if (formType.value === 'create') {
      await KnowledgeApi.createKnowledge(data)
      message.success(t('common.createSuccess'))
    } else {
      await KnowledgeApi.updateKnowledge(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    knowName: undefined,
    chapter: undefined,
    bookId: undefined,
    grade: undefined,
    bookName: undefined,
    knowUrl: '',
  }
  formRef.value?.resetFields()
}

onMounted(() => {
  getBooksList()
})
/** 查询书籍列表 */
const bookList = ref()
const getBooksList = async () => {
  const queryParams = {
    pageNo: 1,
    pageSize: 100,
  }
  try {
    const data = await BookApi.getBookPage(queryParams)
    bookList.value = data.list
    console.log(bookList.value)
  } catch (e) {
    bookList.value = undefined
    console.log("获取书籍失败")
  }
}

const choiceOption = (value: string) => {
  const choiceBook = computed(() => bookList.value.find(item => item.id === value));
  formData.value.grade = choiceBook.value.grade
  formData.value.bookName= choiceBook.value.bookName

}
</script>
